package com.yanqu;

import com.yanqu.jdbc.JdbcTemplateHelper;
import com.yanqu.manager.*;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.executor.ScheduledThreadPoolHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.service.DataFileWrite;
import com.yanqu.timer.GeneralTimerMgr;
import com.yanqu.timer.SaveDataTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.util.concurrent.ScheduledExecutorService;

public class CollectServer {

    // 定时器线程池
    protected static ScheduledExecutorService timerScheduledExecutorService;

    private static DataFileWrite fileWrite;

    private static GoodsMonitorKafkaConsumer goodsMonitorKafkaConsumer;

    private static LogKafkaConsumer logKafkaConsumer;

    private static final Logger logger = LogManager.getLogger(CollectServer.class.getName());

    private static String configPath;

    public static boolean start(){
        try {

            initTimerExecutor();

            configPath = ResourceUtils.getFile("").getAbsolutePath() + File.separator+ "config" +File.separator;
            //文件
            fileWrite = new DataFileWrite();

            //是GoodsMonitorKafkaConsumer还是LogKafkaConsumer,只能有一个
            String serverType = ConfigHelper.getValue("serverType");
            if(!StringUtils.isNullOrEmpty(serverType)){
                if("1".equals(serverType)) {
                    JdbcTemplateHelper.init();

                    goodsMonitorKafkaConsumer = new GoodsMonitorKafkaConsumer();

                    //加载监控数据
                    boolean load = new UserGetGoodsMonitorMgr().init();
                    load = load && new UserGoodsMonitorSettingMgr().init();
                    if (!load) {
                        return false;
                    }
                    new DictMgr().init();
                }else {
                    logKafkaConsumer = new LogKafkaConsumer();
                }
            }
            GeneralTimerMgr.initGlobalTimers();


            //注册异常关闭处理过程
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {

                try {

                    logger.info("CollectServer kill 关闭服务器");

                    GeneralTimerMgr.stop();

                    if (goodsMonitorKafkaConsumer != null) {
                        goodsMonitorKafkaConsumer.close();
                    }

                    if (logKafkaConsumer != null) {
                        logKafkaConsumer.close();
                    }

                    Thread.sleep(3000);

                    fileWrite.close();

                    logger.info("------------");
                    logger.info("------------");
                    logger.info("------------");
                    logger.info("------------");

                    new SaveDataTask().doRun();

                    logger.info("notify process stop success!");
                    Runtime.getRuntime().halt(1);

                }catch (Exception e){
                    logger.error("CollectServer stop error", e);
                }

            }));

            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }


    private static void initTimerExecutor() {
        int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
        corePoolSize = Math.min(8, Math.max(4, corePoolSize));
        timerScheduledExecutorService = ScheduledThreadPoolHelper.createGameScheduledThreadPoolExecutor(corePoolSize, "timer-collectServer");
    }

    public static String getConfigPath() {
        return configPath;
    }

    public static DataFileWrite getFileWrite() {
        return fileWrite;
    }

    public static GoodsMonitorKafkaConsumer getGoodsMonitorKafkaConsumer() {
        return goodsMonitorKafkaConsumer;
    }

    public static LogKafkaConsumer getLogKafkaConsumer() {
        return logKafkaConsumer;
    }

    public static ScheduledExecutorService getTimerScheduledExecutorService() {
        return timerScheduledExecutorService;
    }
}
